package pack1;

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[]arr={3,5,6,88,99,2,1,5,};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void createHeap(int[]arr,int len){
        for (int p = (len-1-1)/2; p >=0; p--) {
            shiftDown(arr,p, arr.length);
        }
    }

    public static void shiftDown(int[]arr,int root,int len){
        int parent=root;
        int child=root*2+1;
        while (child<len){
            if(child+1<len&&arr[child]<arr[child+1]){
                child++;
            }
            if(arr[child]>arr[parent]){
                swap(arr,parent,child);
            }
            parent=child;
            child=child*2+1;
        }
    }

    public static void swap(int[]arr,int i,int j){
        int temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }

    public static void heapSort(int[]arr){
        createHeap(arr,arr.length);
        int end=arr.length-1;
        while(end>=0){
            swap(arr,0,end);
            shiftDown(arr,0,end);
            end--;
        }


    }
}
